import axios from 'axios'
import { errorCodeType } from './error-code-type'
import { ElMessage } from 'element-plus'
import local from '@/utils/local'

/** 创建axios实例 */
const service = axios.create({
  timeout: 100000, // 超时时间
  baseURL: import.meta.env.VITE_APP_BASEURL,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

//2. 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 是否需要设置 token放在请求头
    const token = local.getToken('t_k')
    // 请求头统一携带token
    if (token) {
      config.headers.access_token = token
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

//3. 响应拦截器
service.interceptors.response.use(
  (response) => {
    const code = response.data['code']
    const message = response.data['message']
    // 获取错误信息
    const msg = errorCodeType(code, message)
    if (code === 200) {
      return Promise.resolve(response.data)
    } else {
      ElMessage.error(msg)
      return Promise.reject(response.data)
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default service
